<template>
  <!-- 维度配置页面 -->
  <div>
    <el-row>
      <el-col style="margin-right: 10px" :span="24" class="content-left">
        <el-row class="handleBox">
          <el-col :span="18">
            <template>
              <el-button @click="edit('add')">新增</el-button>
              <el-button @click="edit('edit')">编辑</el-button>
              <el-button @click="del()">删除</el-button>
            </template>
          </el-col>
          <el-col :span="6">
            <div class="handleIconBox">
              <el-popover
                placement="bottom"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="search_porper">
                  <el-form
                    :model="form"
                    ref="form"
                    label-width="110px"
                    label-position="left"
                    size="mini"
                  >
                    <el-form-item label="字段中文名：" prop="fieldName">
                      <el-input
                        v-model="form.fieldName"
                        placeholder="请输入"
                      ></el-input>
                    </el-form-item>
                    <el-form-item label="是否口径：" prop="isCaliber">
                      <el-select
                        clearable
                        v-model="form.isCaliber"
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="item in isCaliberOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="选择类型：" prop="fieldType">
                      <el-select
                        v-model="form.fieldType"
                        placeholder="请选择"
                        clearable
                      >
                        <el-option
                          v-for="item in fieldTypeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        ></el-option>
                      </el-select>
                    </el-form-item>
                  </el-form>
                  <div style="text-align: center; padding: 10px">
                    <el-button
                      size="mini"
                      @click="(form.page = 1), submitForm('form')"
                      >查询</el-button
                    >
                    <el-button size="mini" @click="searchClear">重置</el-button>
                  </div>
                </div>
                <i
                  class="iconfont icon-sousuo"
                  title="搜索"
                  slot="reference"
                ></i>
              </el-popover>
              <el-popover
                placement="bottom"
                width="150"
                trigger="click"
                popper-class="icon_porper"
              >
                <div class="operation_checkbox">
                  <el-checkbox-group v-model="checkList">
                    <el-checkbox
                      v-for="item in textData"
                      :label="item.label"
                      :key="item.prop"
                      >{{ item.label }}
                    </el-checkbox>
                  </el-checkbox-group>
                </div>
                <i
                  class="iconfont icon-liebiaoshezhi"
                  title="列表设置"
                  slot="reference"
                ></i>
              </el-popover>
            </div>
          </el-col>
        </el-row>
      </el-col>
    </el-row>

    <!-- 表格 -->
    <el-table ref="multipleTable" :data="tableData" @row-click="rowClick">
      <el-table-column
        v-if="columnState[0]"
        width="55"
        type="selection"
        
      ></el-table-column>
      <el-table-column
        v-if="columnState[1]"
        prop="fieldEn"
        label="字段英文名"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="columnState[2]"
        prop="fieldName"
        label="字段中文名"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="columnState[3]"
        prop="isCaliber"
        label="是否口径"
        align="center"
      >
        <template slot-scope="scope">{{
          isCaliberFormatter(scope.row)
        }}</template>
      </el-table-column>
      <el-table-column
        v-if="columnState[4]"
        prop="isIdxAttr"
        label="是否指标维度"
        align="center"
      >
        <template slot-scope="scope">{{
          isIdxAttrFormatter(scope.row)
        }}</template>
      </el-table-column>
      <el-table-column
        v-if="columnState[5]"
        prop="fieldType"
        label="选择类型"
        align="center"
      >
        <template slot-scope="scope">{{
          fieldTypeFormatter(scope.row)
        }}</template>
      </el-table-column>
      <el-table-column
        v-if="columnState[6]"
        prop="tableName"
        label="表名"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="columnState[7]"
        prop="tableField"
        label="表字段"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="columnState[8]"
        prop="tableFieldNameFiled"
        label="表字段显示名称"
        align="center"
      ></el-table-column>
      <el-table-column
        v-if="columnState[9]"
        prop="tableFieldSuperior"
        label="表字段上级"
        align="center"
      ></el-table-column>
    </el-table>
    <pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="form.page"
      @refresh="generalQuery"
      :page-size="form.size"
      :total="total"
    ></pagination>
    <!-- 新增、编辑弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="displayEditForm" width="50%">
      <el-form
        :model="editForm"
        ref="editForm"
        :rules="editRules"
        size="small"
        :inline="true"
        label-position="right"
        label-width="130px"
      >
        <el-row
          type="flex"
          justify="space-around"
          style="height: 40px; margin-bottom: 8px"
        >
          <el-form-item
            label="字段英文名："
            style="margin-bottom: 0px"
            prop="fieldEn"
          >
            <el-input
              clearable
              :disabled="disabledWhenEdit"
              style="width: 170px"
              v-model.trim="editForm.fieldEn"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="字段中文名："
            style="margin-bottom: 0px"
            prop="fieldName"
          >
            <el-input
              clearable
              style="width: 170px"
              v-model.trim="editForm.fieldName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row
          type="flex"
          justify="space-around"
          style="height: 40px; margin-bottom: 8px"
        >
          <el-form-item
            label="是否口径："
            style="margin-bottom: 0px"
            prop="isCaliber"
          >
            <el-select
              clearable
              style="width: 170px"
              v-model="editForm.isCaliber"
              placeholder="请选择"
            >
              <el-option
                v-for="item in isCaliberOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否指标维度："
            style="margin-bottom: 0px"
            prop="isIdxAttr"
          >
            <el-select
              clearable
              style="width: 170px"
              v-model="editForm.isIdxAttr"
              placeholder="请选择"
            >
              <el-option
                v-for="item in isIdxAttrOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row
          type="flex"
          justify="space-around"
          style="height: 40px; margin-bottom: 8px"
        >
          <el-form-item
            label="选择类型："
            style="margin-bottom: 0px"
            prop="fieldType"
          >
            <el-select
              clearable
              style="width: 170px"
              v-model="editForm.fieldType"
              placeholder="请选择"
            >
              <el-option
                v-for="item in fieldTypeOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="表名："
            style="margin-bottom: 0px"
            prop="tableName"
          >
            <el-input
              clearable
              style="width: 170px"
              v-model.trim="editForm.tableName"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around" style="height: 40px">
          <el-form-item
            label="表字段："
            style="margin-bottom: 0px"
            prop="tableField"
          >
            <el-input
              clearable
              style="width: 170px"
              v-model.trim="editForm.tableField"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="表字段显示名称："
            style="margin-bottom: 0px"
            prop="tableFieldNameFiled"
          >
            <el-input
              clearable
              style="width: 170px"
              v-model.trim="editForm.tableFieldNameFiled"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around" style="height: 40px">
          <el-form-item
            label="表字段上级："
            style="margin-bottom: 0px"
            prop="tableFieldSuperior"
          >
            <el-input
              clearable
              style="width: 170px"
              v-model.trim="editForm.tableFieldSuperior"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="是否层级汇总："
            style="margin-bottom: 0px"
            prop="isSuperSum"
          >
            <el-select
              clearable
              style="width: 170px"
              v-model="editForm.isSuperSum"
              placeholder="请选择"
            >
              <el-option
                v-for="item in isSuperSumOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="space-around" style="height: 40px">
          <el-form-item
            clearable
            label="汇总表及字段："
            style="margin-bottom: 0px"
            prop="sumTable"
          >
            <el-input
              style="width: 170px"
              v-model.trim="editForm.sumTable"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
          <el-form-item
            clearable
            label="维度映射字段："
            style="margin-bottom: 0px"
            prop="fieldResult"
          >
            <el-input
              style="width: 170px"
              v-model.trim="editForm.fieldResult"
              placeholder="请输入"
            ></el-input>
          </el-form-item>
        </el-row>
        <el-row type="flex" justify="center">
          <el-form-item>
            <el-button @click="checkUnique()">保存</el-button>
          </el-form-item>
          <el-form-item>
            <el-button @click="displayEditForm = false">关闭</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { DatasCenter } from "@/api/index";
export default {
  data() {
    return {
      checkList: [],
      form: {
        fieldName: "", //字段中文名
        isCaliber: "", //是否口径
        fieldType: "", //选择类型
        page: 1,
        size: 15,
      },
      fieldTypeOptions: [], //选择类型-选项列表
      isCaliberOptions: [], //是否口径-选项列表
      isIdxAttrOptions: [], //是否指标维度-选项列表
      isSuperSumOptions: [], //是否层级汇总-选项列表
      total: 0, //总条数
      page: 1, //当前页
      size: 15, //每页条数
      tableData: [], //表格数据
      displayEditForm: false, //显示编辑框弹窗

      // 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      // 000000000000000000000000000000  新增、编辑弹窗 start  000000000000000000000000000000000000000000000
      // 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      addOrEdit: "", //标识新增or编辑
      dialogTitle: "", //标题
      disabledWhenEdit: "", //编辑时禁用输入框
      editForm: {
        //弹窗的表单
        fieldEn: "", //字段英文名
        fieldName: "", //字段中文名
        isCaliber: "", //是否口径
        isIdxAttr: "", //是否指标维度
        fieldType: "", //选择类型
        tableName: "", //表名
        tableField: "", //表字段
        tableFieldNameFiled: "", //表字段显示名称
        tableFieldSuperior: "", //表字段上级
        isSuperSum: "", //是否层级汇总
        sumTable: "", //汇总表及字段
        fieldResult: "", //维度映射字段
      },
      editRules: {
        //校验规则
        fieldEn: [
          {
            required: true,
            message: "请输入字段英文名",
            trigger: "change",
          },
        ],
        fieldName: [
          {
            required: true,
            message: "请输入字段中文名",
            trigger: "change",
          },
        ],
        isCaliber: [
          {
            required: true,
            message: "请选择是否口径",
            trigger: "change",
          },
        ],
        fieldType: [
          {
            required: true,
            message: "请选择类型",
            trigger: "change",
          },
        ],
      },

      // 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      // 000000000000000000000000000000  删除弹窗 start  000000000000000000000000000000000000000000000
      // 00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
      delRow: [], //要删除的行
      textData: [
        { prop: "fieldEn", label: "字段英文名" },
        { prop: "fieldName", label: "字段中文名" },
        { prop: "isCaliber", label: "是否口径" },
        { prop: "isIdxAttr", label: "是否指标维度" },
        { prop: "fieldType", label: "选择类型" },
        { prop: "tableName", label: "表名" },
        { prop: "tableField", label: "表字段" },
        { prop: "tableFieldNameFiled", label: "表字段显示名称" },
        { prop: "tableFieldSuperior", label: "表字段上级" },
      ],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.getDict();
      let params = {
        page: this.page,
        size: this.size,
        total: this.count,
      };
      DatasCenter.findPageFlexibleModel(params)
        .then((response) => this.handleQueryResult(response))
        .catch(function (error) {
          console.log(error);
        });
    });
  },
  created() {
    this.checkListInit();
  },
  computed: {
    columnState() {
      console.log(this.checkList);
      let arr = [],
        arr1 = this.textData,
        arr2 = this.checkList;
      for (let i = 0; i < arr1.length; i++) {
        let flg = false;
        for (let j = 0; j < arr2.length; j++) {
          if (arr1[i].label === arr2[j]) {
            flg = true;
          }
        }
        arr.push(flg);
      }
      return arr;
    },
    // 展示字段
    showData() {
      let arr = this.textData.map((v) => {
        return v.label;
      });
      let valArr = [],
        showData = [];
      // 选中的字段排序
      arr.forEach((element) => {
        let flag = false;
        this.checkList.forEach((e) => {
          if (e == element) {
            flag = true;
          }
        });
        if (flag) {
          valArr.push(element);
        }
      });
      // 控制表列隐藏显示
      for (let i = 0; i < this.checkList.length; i++) {
        for (let j = 0; j < this.textData.length; j++) {
          if (this.textData[j].label == valArr[i]) {
            let item = { ...this.textData[j] };
            showData.push(item);
          }
        }
      }
      return showData;
    },
  },
  methods: {
    checkListInit() {
      this.checkList = this.textData.map((v) => {
        return v.label;
      });
    },
    searchClear() {
      for (const key in this.form) {
        this.form[key] = "";
      }
      this.form.page = 1;
      this.form.size = 15;
    },
    rowClick(row) {
      this.$refs.multipleTable.clearSelection();
      this.$refs.multipleTable.toggleRowSelection(row, true);
    },
    getDict() {
      // 获取字典数据
      this.$getDict("is_caliber").then((res) => {
        if (res.code == 200) {
          this.isCaliberOptions = res.datas;
        }
      });
      this.$getDict("field_type").then((res) => {
        if (res.code == 200) {
          this.fieldTypeOptions = res.datas;
        }
      });
      this.$getDict("is_or_not").then((res) => {
        if (res.code == 200) {
          this.isIdxAttrOptions = res.datas;
        }
      });
      this.$getDict("sys_orgDeptFlag").then((res) => {
        if (res.code == 200) {
          this.isSuperSumOptions = res.datas;
        }
      });
    },
    generalQuery() {
      //通用查询
      let params = {
        fieldName: this.form.fieldName,
        isCaliber: this.form.isCaliber,
        fieldType: this.form.fieldType,
        page: this.form.page,
        size: this.form.size,
        total: this.total,
      };
      DatasCenter.findPageFlexibleModel(params)
        .then((res) => {
          this.handleQueryResult(res);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    handleQueryResult(response) {
      //处理查询结果
      this.tableData = response.data;
      this.total = response.count;
    },
    submitForm() {
      //提交表单
      this.page = 1;
      this.generalQuery();
    },
    resetForm(formName) {
      //重置表单
      this.$refs[formName].resetFields();
    },
    isCaliberFormatter(row) {
      //是否口径-格式化
      if (row.isCaliber == null) {
        return "";
      }
      if (row.isCaliber === "0") {
        return "否";
      }
      if (row.isCaliber === "1") {
        return "是";
      }
    },
    isIdxAttrFormatter(row) {
      //是否指标维度-格式化
      if (row.isIdxAttr == null) {
        return "";
      }
      if (row.isIdxAttr === "0") {
        return "否";
      }
      if (row.isIdxAttr === "1") {
        return "是";
      }
    },
    fieldTypeFormatter(row) {
      //选择类型-格式化
      if (row.fieldType == null) {
        return "";
      }
      if (row.fieldType === "tree") {
        return "树型";
      }
      if (row.fieldType === "grid") {
        return "网络型";
      }
      if (row.fieldType === "dict") {
        return "数据字典型";
      }
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.form.size = val;
      this.generalQuery();
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.form.page = val;
      this.generalQuery();
    },
    handlePaginationCurrent(value) {
      //页数改变
      this.page = Number(value);
      this.generalQuery();
      window.removeEventListener("keydown", function () {});
    },
    handlePaginationRefresh(boolean) {
      //刷新按钮
      boolean && this.generalQuery();
    },
    handlePaginationSizes(value) {
      //每页多少条改变
      this.size = Number(value);
      this.page = 1;
      this.generalQuery();
    },
    edit(val) {
      this.addOrEdit = val;
      if (this.addOrEdit === "add") {
        this.dialogTitle = "新增";
        (this.editForm.fieldEn = ""), //字段英文名
          (this.editForm.fieldName = ""), //字段中文名
          (this.editForm.isCaliber = ""), //是否口径
          (this.editForm.isIdxAttr = ""), //是否指标维度
          (this.editForm.fieldType = ""), //选择类型
          (this.editForm.tableName = ""), //表名
          (this.editForm.tableField = ""), //表字段
          (this.editForm.tableFieldNameFiled = ""), //表字段显示名称
          (this.editForm.tableFieldSuperior = ""), //表字段上级
          (this.editForm.isSuperSum = ""), //是否层级汇总
          (this.editForm.sumTable = ""), //汇总表及字段
          (this.editForm.fieldResult = ""), //维度映射字段
          (this.disabledWhenEdit = false);
        this.displayEditForm = true;
      }
      if (this.addOrEdit === "edit") {
        let selection = this.$refs.multipleTable.selection;
        if (selection.length != 1) {
          return this.$message.warning("请选择一条数据进行修改");
        }
        let row = selection[0];
        this.dialogTitle = "编辑";
        this.editForm.fieldEn = row.fieldEn; //字段英文名
        this.editForm.fieldName = row.fieldName; //字段中文名
        this.editForm.isCaliber = row.isCaliber; //是否口径
        this.editForm.isIdxAttr = row.isIdxAttr; //是否指标维度
        this.editForm.fieldType = row.fieldType; //选择类型
        this.editForm.tableName = row.tableName; //表名
        this.editForm.tableField = row.tableField; //表字段
        this.editForm.tableFieldNameFiled = row.tableFieldNameFiled; //表字段显示名称
        this.editForm.tableFieldSuperior = row.tableFieldSuperior; //表字段上级
        this.editForm.isSuperSum = row.isSuperSum; //是否层级汇总
        this.editForm.sumTable = row.sumTable; //汇总表及字段
        this.editForm.fieldResult = row.fieldResult; //维度映射字段
        this.disabledWhenEdit = true;
        this.displayEditForm = true;
      }
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
      });
    },
    checkUnique() {
      //保存
      var formName = "editForm";
      var ot = this.addOrEdit === "add" ? 1 : 2;
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let params = {
            fieldEn: this.editForm.fieldEn,
            fieldName: this.editForm.fieldName,
            isCaliber: this.editForm.isCaliber,
            isIdxAttr: this.editForm.isIdxAttr,
            fieldType: this.editForm.fieldType,
            tableName: this.editForm.tableName,
            tableField: this.editForm.tableField,
            tableFieldNameFiled: this.editForm.tableFieldNameFiled,
            tableFieldSuperior: this.editForm.tableFieldSuperior,
            isSuperSum: this.editForm.isSuperSum,
            sumTable: this.editForm.sumTable,
            fieldResult: this.editForm.fieldResult,
            operateType: ot,
          };
          DatasCenter.checkUniqueFlexibleModel(params)
            .then((response) => this.handleCheckUnique(response))
            .catch(function (error) {
              console.log(error);
              this.$message({
                showClose: true,
                message: "请求发送失败",
                type: "error",
                center: true,
              });
            });
        } else {
          //校验没通过
          return false;
        }
      });
    },
    handleCheckUnique(response) {
      //处理checkUnique
      var ot = this.addOrEdit === "add" ? 1 : 2;
      if (response.data == true) {
        let params = {
          fieldEn: this.editForm.fieldEn,
          fieldName: this.editForm.fieldName,
          isCaliber: this.editForm.isCaliber,
          isIdxAttr: this.editForm.isIdxAttr,
          fieldType: this.editForm.fieldType,
          tableName: this.editForm.tableName,
          tableField: this.editForm.tableField,
          tableFieldNameFiled: this.editForm.tableFieldNameFiled,
          tableFieldSuperior: this.editForm.tableFieldSuperior,
          isSuperSum: this.editForm.isSuperSum,
          sumTable: this.editForm.sumTable,
          fieldResult: this.editForm.fieldResult,
          operateType: ot,
        };
        DatasCenter.saveFlexibleModel(params)
          .then((response) => this.handleSave(response))
          .catch(function (error) {
            console.log(error);
            this.$message({
              showClose: true,
              message: "请求发送失败",
              type: "error",
              center: true,
            });
          });
      } else {
        this.$message({
          showClose: true,
          message: "数据已存在，保存失败！",
          type: "error",
          center: true,
        });
        this.displayEditForm = false;
      }
    },
    handleSave(response) {
      //处理save
      if (response.code == 200) {
        this.$message({
          type: "success",
          message: "保存成功!",
        });
        this.displayEditForm = false;
        this.generalQuery();
      } else {
        this.$message({
          showClose: true,
          message: "服务器异常，保存失败！",
          type: "error",

          center: true,
        });
      }
    },

    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    //////////////////////////////////////////////////////// 删除弹窗 start///////////////////////////////////////////////////////
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    del() {
      //删除按钮
      let selection = this.$refs.multipleTable.selection;
      if (selection.length < 1) {
        return this.$message.warning("请选择要删除的数据");
      }
      this.$confirm("删除这条数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.delRow = selection;
          let params = {
            // fieldEn: this.delRow.fieldEn,
            ids: this.delRow.map((v) => v.fieldEn),
          };
          DatasCenter.referenchCheckFlexibleModel(params)
            .then((response) => this.handleReferenceCheck(response))
            .catch(function (error) {
              console.log(error);
              this.$message({
                showClose: true,
                message: "请求发送失败",
                type: "error",
                center: true,
              });
            });
        })
        .catch(() => {
          // 取消删除
        });
    },
    handleReferenceCheck(response) {
      //处理删除前的检查结果
      console.log("删除的结果", this.delRow);
      if (response.message == "1") {
        this.realRemove();
      } else {
        this.$message({
          type: "warning",
          message: "不能删除已经被引用的维度",
        });
      }
    },
    realRemove() {
      //真正删除
      let params = {
        ids: this.delRow.map((v) => v.fieldEn),
      };
      DatasCenter.removeFlexibleModel(params)
        .then((response) => this.handleRemove(response))
        .catch(function () {
          this.$message({
            type: "error",
            message: "删除失败",
          });
        });
    },
    handleRemove(response) {
      //处理删除结果
      if (response.code == 200) {
        this.$message({
          type: "success",
          message: "删除成功!",
        });
        this.generalQuery();
      } else {
        this.$message({
          type: "warning",
          message: "删除失败!",
        });
      }
    },
  },
};
</script>
